<template>
  <ContentWrap>
    <div class="customer-type-filter mb-10px flex flex-wrap items-center gap-3">
      <el-button
        v-for="dict in customerTypeList"
        v-hasPermi="dict.permi"
        :key="dict.value"
        :type="queryParams.customerType === dict.value ? 'primary' : 'default'"
        :plain="queryParams.customerType !== dict.value"
        @click="handleCustomerTypeFilter(dict.value)"
        size="default"
        class="filter-btn rounded-full px-5 py-2 transition-all duration-300 hover:shadow-md font-medium"
        round
      >
        {{ dict.label }}
      </el-button>
      <el-alert
        v-if="!hasAnyCustomerTypePermission"
        title="您没有访问任何客户类型的权限，请联系管理员分配权限"
        type="warning"
        :closable="false"
        style="width: max-content; padding-top: 2px; padding-bottom: 2px;"
      />

      <el-button @click="handleQuery" style="margin-left: auto"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
      <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
      <el-button
        type="primary"
        plain
        @click="openForm('create')"
        v-hasPermi="['system:customer:create']"
      >
        <Icon icon="ep:plus" class="mr-5px" /> 新增
      </el-button>
      <el-button
        type="success"
        plain
        @click="handleExport"
        :loading="exportLoading"
        v-hasPermi="['system:customer:export']"
      >
        <Icon icon="ep:download" class="mr-5px" /> 导出
      </el-button>
      <el-button
        type="warning"
        plain
        @click="handleImport"
        v-hasPermi="['system:customer:import']"
      >
        <Icon icon="ep:upload" /> 导入
      </el-button>
      <el-button
        type="danger"
        plain
        :disabled="isEmpty(checkedIds)"
        @click="handleDeleteBatch"
        v-hasPermi="['system:customer:delete']"
      >
        <Icon icon="ep:delete" class="mr-5px" /> 批量删除
      </el-button>
    </div>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px query-form"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
    >
      <el-form-item label="客户姓名" prop="username">
        <el-input
          v-model="queryParams.username"
          placeholder=""
          clearable
          @keyup.enter="handleQuery"
          style="width: 100px;"
        />
      </el-form-item>
      <el-form-item label="跟进状态" prop="followUpStatus">
        <el-select
          v-model="queryParams.followUpStatus"
          placeholder=""
          clearable
          style="width: 90px;"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.FOLLOWUPSTATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="来源" prop="source">
        <el-select
          v-model="queryParams.source"
          placeholder=""
          clearable
          style="width: 120px;"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CRM_CUSTOMER_SOURCE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="客户星级" prop="starRating">
        <el-select
          v-model="queryParams.starRating"
          placeholder=""
          clearable
          style="width: 50px;"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CUSTOMERSTARRATING)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="房产" prop="realestate">
        <el-select
          v-model="queryParams.realestate"
          placeholder=""
          clearable
          style="width: 70px;"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.REALESTATE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="公积金" prop="housingProvidentFund">
        <el-select
          v-model="queryParams.housingProvidentFund"
          placeholder=""
          clearable
          style="width: 80px;"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.HOUSINGPROVIDENTFUND)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="社保" prop="socialinsurance">
        <el-select
          v-model="queryParams.socialinsurance"
          placeholder=""
          clearable
          style="width: 70px;"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.SOCIALINSURANCE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="跟进时间" prop="followTime">
        <el-date-picker
          v-model="queryParams.followTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          clear-icon=""
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          style="width: 140px;"
        />
      </el-form-item>
      <el-form-item label="申请时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          clear-icon=""
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          style="width: 140px;"
        />
      </el-form-item>
      <el-form-item label="手机号码" prop="mobile">
        <el-input
          v-model="queryParams.mobile"
          placeholder=""
          type="tel"
          clearable
          @keyup.enter="handleQuery"
          style="width: 100px;"
        />
      </el-form-item>
      <el-form-item
        v-if="!['公海客户'].includes(getDictLabel(DICT_TYPE.CUSTOMER_TYPE, queryParams.customerType))"
        label="业务经理"
      >
        <el-select
          v-loading="loading"
          v-model="queryParams.followUp"
          @change="() => handleQuery()"
          placeholder=""
          clearable
          style="width: 120px;"
        >
          <el-option
            v-for="item in followUpList"
            :key="item.id"
            :value="item.id"
            :label="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item> 
        <el-button
          v-show="['公海客户','再分配客户','我的客户'].includes(getDictLabel(DICT_TYPE.CUSTOMER_TYPE, queryParams.customerType))"
          v-hasPermi="['system:customer:assign']"
          :disabled="!checkedIds.length"
          :loading="loading"
          type="primary"
          plain
          @click="() => showAssignDialog({ ids: checkedIds, customerType: queryParams.customerType })"
        >
          分配
        </el-button>
        <el-button
          v-show="['公海客户'].includes(getDictLabel(DICT_TYPE.CUSTOMER_TYPE, queryParams.customerType))"
          :disabled="!checkedIds.length"
          :loading="loading"
          type="primary"
          plain
          @click="() => handleTake(checkedIds)"
        >
          领取
        </el-button>
        <el-button
          v-show="['再分配客户','我的客户'].includes(getDictLabel(DICT_TYPE.CUSTOMER_TYPE, queryParams.customerType))"
          :disabled="!checkedIds.length"
          :loading="loading"
          type="success"
          plain
          @click="() => handleMovingIntoImportant(checkedIds)"
        >
          标为重要客户
        </el-button>
        <el-button
          v-show="['再分配客户'].includes(getDictLabel(DICT_TYPE.CUSTOMER_TYPE, queryParams.customerType))"
          :disabled="!checkedIds.length"
          :loading="loading"
          type="warning"
          plain
          @click="() => handleMyCustomer(checkedIds)"
        >
          移入我的客户
        </el-button>
        <el-button
          v-show="['重要客户'].includes(getDictLabel(DICT_TYPE.CUSTOMER_TYPE, queryParams.customerType))"
          :disabled="!checkedIds.length"
          :loading="loading"
          type="danger"
          plain
          @click="() => handleMovingOutImportant(checkedIds)"
        >
          移出重要客户
        </el-button>
        <el-button
          v-show="['再分配客户','重要客户','我的客户'].includes(getDictLabel(DICT_TYPE.CUSTOMER_TYPE, queryParams.customerType))"
          :disabled="!checkedIds.length"
          :loading="loading"
          type="warning"
          plain
          @click="() => handleMovingIntoOpensea(checkedIds)"
        >
          移入公海客户
        </el-button>
        <section
          v-show="
            hasAnyCustomerTypePermission &&
            !['公海客户'].includes(getDictLabel(DICT_TYPE.CUSTOMER_TYPE, queryParams.customerType))
          "
          class="count-info"
        >
          <p>
            今日0星数据：
            <a
              class="value"
              @click.prevent="() => toCountDetail('todayStarZero')">{{ countInfo.todayStarZero }}条
            </a>，
            今日0星占比：
            <a class="value" style="text-decoration: none;">{{ countInfo.percentage }}</a>，
            0星数据共计：<a class="value" @click.prevent="() => toCountDetail('total')">{{ countInfo.total }}条</a>，
          </p>
          <p>
            5天未跟进客户：<a class="value" @click.prevent="() => toCountDetail('notFollowedUpFive')">{{ countInfo.notFollowedUpFive }}条</a>（其中2星以上<a class="value" @click.prevent="() => toCountDetail('notFollowedUpFiveStarTwo')">{{ countInfo.notFollowedUpFiveStarTwo }}条</a>），
            7天未跟进客户：<a class="value" @click.prevent="() => toCountDetail('notFollowedUpSeven')">{{ countInfo.notFollowedUpSeven }}条</a>（其中2星以上<a class="value" @click.prevent="() => toCountDetail('notFollowedUpSevenStarTwo')">{{ countInfo.notFollowedUpSevenStarTwo }}条</a>）
          </p>
        </section>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <template v-if="hasAnyCustomerTypePermission">
      <el-table
        row-key="id"
        v-loading="loading"
        border
        :data="list"
        :stripe="true"
        :show-overflow-tooltip="true"
        :select-on-indeterminate="false"
        :height="540"
        :row-style="({ row }) => (0 === row.status ? { color: 'red' } : {})"
        @row-click="handleRowClick"
        @selection-change="handleRowCheckboxChange"
        @sort-change="handleSortChange"
      >
        <template #empty>
          <el-empty description="暂无数据" />
        </template>
        <el-table-column :resizable="false" type="selection" align="center" width="40px" fixed="left" />
        <el-table-column :resizable="false" label="姓名" align="center" prop="username"  />
        <el-table-column :resizable="false" label="年龄" align="center" prop="age"  />
        <el-table-column :resizable="false" label="性别" align="center" prop="sex" >
          <template #default="scope">
            {{ getDictLabel(DICT_TYPE.SYSTEM_USER_SEX, scope.row.sex) }}
          </template>
        </el-table-column>
        <el-table-column :resizable="false" label="额度" align="center" prop="quota" />
        <el-table-column :resizable="false" label="跟进人" align="center" prop="followUpName"  />
        <el-table-column :resizable="false" label="跟进状态" align="center" prop="followUpStatus" >
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.FOLLOWUPSTATUS" :value="scope.row.followUpStatus" />
          </template>
        </el-table-column>
        <el-table-column :resizable="false" label="客户星级" align="center" prop="starRating" >
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.CUSTOMERSTARRATING" :value="scope.row.starRating" />
          </template>
        </el-table-column>
        <el-table-column :resizable="false" label="客户属性" align="center" >
          <template #default="{ row }">
            <template v-if="!CustomerProps(row).length">无</template>
            {{ CustomerProps(row) }}
            <!-- <div class="tag-group">
            </div> -->
          </template>
        </el-table-column>
        <el-table-column :resizable="false" label="客户条件备注" align="center" prop="remark" width="145px" />
        <el-table-column :resizable="false" label="跟进情况备注" align="center" prop="followRemark" width="145px" />
        <el-table-column :resizable="false" label="跟进次数" align="center" prop="followUpFrequency" />
        <el-table-column :resizable="false" label="来源" align="center" prop="source" width="145px">
          <template #default="scope">
            {{ getDictLabel(DICT_TYPE.CRM_CUSTOMER_SOURCE, scope.row.source) }}
          </template>
        </el-table-column>
        <el-table-column
          :resizable="false"
          label="最后跟进时间"
          align="center"
          prop="followTime"
          :formatter="dateFormatter"
          sortable
          width="145px"
        >
          <template #header>
            最后跟进时间
            <span class="caret-wrapper custom">
              <i :style="{ 'border-bottom-color': 1 === queryParams.sortFollowOrder ? 'var(--el-color-primary)' : 'var(--el-text-color-placeholder)'  }" class="sort-caret ascending"></i>
              <i :style="{ 'border-top-color': 0 === queryParams.sortFollowOrder ? 'var(--el-color-primary)' : 'var(--el-text-color-placeholder)'  }" class="sort-caret descending"></i>
            </span>
          </template>
        </el-table-column>
        <el-table-column
          :resizable="false"
          label="申请时间"
          align="center"
          prop="createTime"
          :formatter="dateFormatter"
          sortable
          width="145px"
        >
          <template #header>
            申请时间
            <span class="caret-wrapper custom">
              <i :style="{ 'border-bottom-color': 1 === queryParams.sortcreateTime ? 'var(--el-color-primary)' : 'var(--el-text-color-placeholder)'  }" class="sort-caret ascending"></i>
              <i :style="{ 'border-top-color': 0 === queryParams.sortcreateTime ? 'var(--el-color-primary)' : 'var(--el-text-color-placeholder)'  }" class="sort-caret descending"></i>
            </span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          :resizable="false"
          align="center"
          width="145px"
          fixed="right">
          <template #default="scope">
            <el-button
              link
              v-if="'公海客户' == getDictLabel(DICT_TYPE.CUSTOMER_TYPE, scope.row.customerType)"
              type="primary"
              @click.stop="() => handleTake([scope.row.id])"
            >
              领取
            </el-button>
            <!-- @click.stop="openForm('update', scope.row.id)" -->
            <el-button
              link
              type="primary"
              @click.stop="() => handleRowClick(scope.row)"
              v-hasPermi="['system:customer:update']"
            >
              详情
            </el-button>
            <el-button
              link
              type="danger"
              @click.stop="handleDelete(scope.row.id)"
              v-hasPermi="['system:customer:delete']"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <Pagination
        :total="total"
        :page-sizes="[50, 100]"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </template>
    <template v-else>
      <el-empty description="您没有访问客户数据的权限" style="height: 540px;" />
    </template>
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <customerForm
    ref="formRef"
    @success="() => {
      getList();
      getCountInfo();
    }"
  />

  <!-- 客户分配 -->
  <AssignDialog ref="assignDialogRef" @submit="handleAssign" />

  <!-- 客户导入表单组件 -->
  <ImportForm
    ref="importFormRef"
    @success="() => {
      getList();
      getCountInfo();
    }"
  />

  <!-- 跟进表单 -->
  <FollowUpDialog
    ref="followUpDialogRef"
    :get-info-method="customerApi.getcustomer"
    :info-list="list"
    :get-info-list-method="getList"
    :save="handleFollowUpSave"
    :get-history-method="info => customerApi.getRemarkHistory({ customerId: info.id })"
    :get-loan-page-method="info => loanApi.getloanPage({ pageNo: 1, pageSize: 30, customerId: info.id})"
    :show-assign-dialog="showAssignDialog"
    @save="getCountInfo"
  />
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE, getDictLabel } from '@/utils/dict'
import { isEmpty } from '@/utils/is'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { customerApi, customer } from '@/api/system/customer'
import customerForm from './customerForm.vue'
import AssignDialog from './AssignDialog.vue'
import ImportForm from './ImportForm.vue'
import FollowUpDialog from './FollowUpDialog.vue'
import dayjs from 'dayjs'
import { cloneDeep, omit } from 'lodash-es'
import { hasPermission } from '@/directives/permission/hasPermi'
import { MyCustomerApi } from '@/api/system/mycustomer'
import { useUserStore } from '@/store/modules/user'
import { loanApi } from '@/api/system/loan'

const userStore = useUserStore();

/** 客户 列表 */
defineOptions({ name: 'Customer' })
const router = useRouter();
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<customer[]>([]) // 列表的数据
provide('infoList', list);
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 50,
  username: undefined,
  sex: undefined,
  age: undefined,
  quota: undefined,
  mobile: undefined,
  createTime: [],
  followUp: undefined,
  followUpName: undefined,
  followUpStatus: undefined,
  remark: undefined,
  followUpFrequency: undefined,
  source: undefined,
  starRating: undefined,
  realestate: undefined,
  housingProvidentFund: undefined,
  socialinsurance: undefined,
  customerType: 2,
  followTime: [],
  /** 正序=1 倒序=0 */
  sortFollowOrder: undefined,
  /** 正序=1 倒序=0 */
  sortcreateTime: undefined,
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const currentRow = ref({}) // 选中行


/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await customerApi.getcustomerPage(queryParams)
    list.value = data.list;
    total.value = data.total;
  } finally {
    loading.value = false
  }
}
provide('getList', getList);

function CustomerProps(row) {
  return [
    {
      type: DICT_TYPE.REALESTATE,
      prop: 'realestate',
      validator: x => [0,1].includes(x),
    },
    {
      type: DICT_TYPE.HOUSINGPROVIDENTFUND,
      prop: 'housingProvidentFund',
      validator: x => [0].includes(x),
    },
    {
      type: DICT_TYPE.SOCIALINSURANCE,
      prop: 'socialinsurance',
      validator: x => [0].includes(x),
    }
  ]
  .filter(item => item.validator(row[item.prop]))
  .map(item => getDictLabel(item.type, row[item.prop]))
  .join('/');
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getCountInfo();
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

function handleSortChange({ column, prop, order }) {
  function Value() {
    // 下标为 -1 则值为 undefined，正好对应不传
    const i = ['descending', 'ascending'].indexOf(order);
    return [0, 1][i];
  }

  function Prop() {
    return {
      followTime: 'sortFollowOrder',
      createTime: 'sortcreateTime',
    }[prop];
  }

  queryParams[Prop()] = Value();
  getList();
}

function handleFollowUpSave(info, infoInitial) {
  // 若某些字段值没变，则不传那些字段值
  // 目前有跟进状态、跟进备注
  const needCheckProps = ['followUpStatus', 'followRemark'];
  const isNoModified = prop => info.value[prop] == infoInitial.value[prop];
  const omitProps = needCheckProps.filter(isNoModified);
  return customerApi.updatecustomer(omit(info.value, omitProps));
}

const countInfo = ref({
  /** 今日0显数据 */
  todayStarZero: 0,

  /** 0星占比 */
  percentage: 0,

  /** 0星条数 */
  total: 0,

  /** 5天未跟进 */
  notFollowedUpFive: 0,

  /** 5天未跟进2星客户 */
  notFollowedUpFiveStarTwo: 0,

  /** 7天未跟进 */
  notFollowedUpSeven: 0,

  /** 7天未跟进2星客户 */
  notFollowedUpSevenStarTwo: 0,
});

function getCountInfo() {
  return customerApi.getCountInfo(queryParams)
  .then(data => {
    data && (countInfo.value = data);
  });
}

function toCountDetail(prop) {
  const genQuery = {
    todayStarZero: () => {
      return {
        createTime: [
          dayjs().startOf('day').format('YYYY-MM-DD HH:mm:ss'),
          dayjs().format('YYYY-MM-DD HH:mm:ss'),
        ],
        starRating: 0,
      };
    },
    total: () => {
      return {
        starRating: 0,
      };
    },
    notFollowedUpFive: () => {
      return {
        followTime: [
          dayjs().subtract(1, 'year').format('YYYY-MM-DD HH:mm:ss'),
          dayjs().subtract(5, 'day').format('YYYY-MM-DD HH:mm:ss'),
        ],
      };
    },
    notFollowedUpFiveStarTwo: () => {
      return {
        starRating: 2,
        followTime: [
          dayjs().subtract(1, 'year').format('YYYY-MM-DD HH:mm:ss'),
          dayjs().subtract(5, 'day').format('YYYY-MM-DD HH:mm:ss'),
        ],
      };
    },
    notFollowedUpSeven: () => {
      return {
        followTime: [
          dayjs().subtract(1, 'year').format('YYYY-MM-DD HH:mm:ss'),
          dayjs().subtract(7, 'day').format('YYYY-MM-DD HH:mm:ss'),
        ],
      };
    },
    notFollowedUpSevenStarTwo: () => {
      return {
        starRating: 2,
        followTime: [
          dayjs().subtract(1, 'year').format('YYYY-MM-DD HH:mm:ss'),
          dayjs().subtract(7, 'day').format('YYYY-MM-DD HH:mm:ss'),
        ],
      };
    },
  };

  loading.value = true;
  return getCountInfo()
    .then(() => {
      router.push({ name: 'CountCustomerDetail', query: Object.assign( cloneDeep(queryParams), genQuery[prop]() ) });
    })
    .finally(() => {
      loading.value = false;
  });
}

const followUpList = ref([]);
function getFollowUpList() {
  return customerApi.getFollowUpList()
  .then(data => {
    followUpList.value = data;
    queryParams.followUp = userStore.getUser.id;
  });
}

function handleMovingIntoImportant(ids) {
  loading.value = true;
  return customerApi.movingIntoImportant({
    ids
  })
  .then(() => {
    ElMessage.success('已标为重要客户');
    return getList();
  })
  .finally(() => {
    loading.value = false;
  });
}

function handleMyCustomer(ids) {
  loading.value = true;
  return customerApi.movingIntoMyCustomer({
    ids
  })
  .then(() => {
    ElMessage.success('已移入我的客户');
    return getList();
  })
  .finally(() => {
    loading.value = false;
  });
}

function handleMovingOutImportant(ids) {
  loading.value = true;
  return customerApi.movingOutImportant({
    ids,
    // followUpId: queryParams.followUp,
    // followUpName: queryParams.followUpName,
  })
  .then(() => {
    ElMessage.success('已移出重要客户');
    return getList();
  })
  .finally(() => {
    loading.value = false;
  });
}

function handleMovingIntoOpensea(ids) {
  loading.value = true;
  return customerApi.movingIntoOpensea({
    ids
  })
  .then(() => {
    ElMessage.success('已移入公海客户');
    return getList();
  })
  .finally(() => {
    loading.value = false;
  });
}
// ---  作用同跟进记录弹框右上 结束 ---

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 公海客户 - 领取 */
function handleTake(ids) {
  if (loading.value) { return }

  loading.value = true
  return customerApi
    .take({
      ids
    })
    .then(() => {
      message.success('已领取')
      return getList()
    })
    .finally(() => {
      loading.value = false
    })
}

function handleMark(row) {
  if (loading.value) { return }

  loading.value = true;
  const data = cloneDeep(row);
  data.customerId = data.id;
  data.id = void 0;
  return MyCustomerApi
    .createMyCustomer(data)
    .then(() => {
      message.success('已标记');
      return getList();
    })
    .finally(() => {
      loading.value = false
    })
}

const assignDialogRef = ref()
function showAssignDialog(formState) {
  assignDialogRef.value.open(formState)
}
provide('showAssignDialog', showAssignDialog);

function handleAssign(payload) {
  if (!Boolean(payload.followUp.id)) {
    message.warning('请先选择分配人员')
    return
  }

  loading.value = true
  // 分配可选多人
  return customerApi
    .assign({
      customerType: payload.customerType,
      ids: payload.ids,
      followUpId: payload.followUp.id,
      followUpName: payload.followUp.nickname
    })
    .then(() => {
      message.success('已分配')
      getList()
      assignDialogRef.value.close()
      return
    })
    .finally(() => {
      loading.value = false
    })
}
provide('handleAssign', handleAssign);

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await customerApi.deletecustomer(id)
    message.success(t('common.delSuccess'))
    currentRow.value = {}
    // 刷新列表
    await getList()
  } catch {}
}

/** 批量删除客户 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await customerApi.deletecustomerList(checkedIds.value)
    checkedRows.value = []
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

const checkedRows = ref<customer[]>([])
const checkedIds = computed<number[]>(() => checkedRows.value.map((item) => item.id))
const handleRowCheckboxChange = (records: customer[]) => {
  checkedRows.value = records
}

const followUpDialogRef = ref();
function handleRowClick(row, column) {
  if (column && 'selection' == column.type) {
    return;
  }
  followUpDialogRef.value.open(list.value.indexOf(row));
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await customerApi.exportcustomer(queryParams)
    download.excel(data, '客户.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 设备导入 */
const importFormRef = ref()
const handleImport = () => {
  importFormRef.value.open()
}

/** 客户类型快速筛选 */
const handleCustomerTypeFilter = (type: number | undefined) => {
  // 重置除 customerType 外的所有查询参数
  const ignoreFields = [
    'customerType',
    'followUp',
    'pageNo',
    'pageSize',
  ];
  Object.keys(queryParams).forEach((key) => {
    if (!ignoreFields.includes(key)) {
      if (Array.isArray(queryParams[key])) {
        queryParams[key] = []
      } else {
        queryParams[key] = undefined
      }
    }
  })
  // 设置新的客户类型
  queryParams.customerType = type
  // 重置页码为第一页
  queryParams.pageNo = 1
  handleQuery()
}

const customerTypeDic = {
  '公海客户': ['system:customer:publiccustomer'],
  '我的客户': ['system:customer:mycustomer'],
  '重要客户': ['system:customer:importantcustomer'],
  '再分配客户': ['system:customer:assignedcustomer'],
  '全部客户': ['system:customer:allcustomer'],
};
const customerTypeList = computed(() => {
  return (
    getIntDictOptions(DICT_TYPE.CUSTOMER_TYPE)
    .concat({
      value: void 0,
      label: '全部客户',
      dictType: 'customer_type',
    })
    .map(item => {
      return Object.assign(
        { permi: customerTypeDic[item.label] },
        item
      )
    })
  )
});

// const customerTypeList = computed(() => {
//   const xs = getIntDictOptions(DICT_TYPE.CUSTOMER_TYPE).filter(item => hasPermission( customerTypeDic[item.label] ));
//   return 0 < xs.length
//     ? xs
//       .concat({
//         value: void 0,
//         label: '全部客户',
//         dictType: 'customer_type',
//       })
//       .map(item => {
//         return Object.assign(
//           { permi: customerTypeDic[item.label] },
//           item
//         )
//       })
//       : xs;
// });

/** 检查用户是否有任一客户类型的操作权限 */
const hasAnyCustomerTypePermission = computed(() => {
  return Object.values(customerTypeDic).some(hasPermission);
});

/** 初始化 **/
onMounted(() => {
  getCountInfo();
  getList();
  getFollowUpList();
})
</script>

<style scoped>
.customer-type-filter {
  background-color: #f5f7fa;
  padding: 6px 10px;
  border-radius: 10px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.customer-type-filter .el-button {
  height: 30px;
  font-size: 12px;
}

.customer-type-filter .el-button + .el-button {
  margin-left: 0;
}

.customer-type-filter .el-button.is-round {
  height: 28px;
}

.query-form {
  display: flex;
  flex-wrap: wrap;
  gap: 4px 12px;
  padding-bottom: 18px;
}

.query-form .el-button {
  height: 24px;
  padding: 4px 10px;
  font-size: 12px;
}

.query-form .el-form-item {
  margin: 0;
}

.query-form :deep(.el-form-item__content) {
  font-size: 12px;
}

.query-form :deep(.el-form-item__label),
.query-form :deep(.el-form-item__content) :where(.el-input, .el-select__wrapper, .el-range-input) {
  font-size: 12px;
}

.query-form :deep(.el-input__inner) {
  --el-input-inner-height: 22px;
}

.query-form :deep(.el-input__wrapper) {
  padding-left: 0;
  padding-right: 4px;
}

.query-form :deep(.el-date-editor .el-range-input) {
  width: 44%;
}

.query-form :deep(.el-date-editor.el-input__wrapper) {
  padding-right: 0;
}

.query-form :deep(.el-select__wrapper) {
  padding-left: 4px;
  padding-right: 6px;
  min-height: 24px;
  height: 22px;
  line-height: 22px;
}

.query-form :where(.el-date-editor.el-input, .el-date-editor.el-input__wrapper) {
  justify-content: left;
  padding-right: 0;
  --el-component-size: 24px;
}

.query-form :deep(.el-date-editor .el-range-separator) {
  flex: 0;
  width: 2px;
  padding-left: 2px;
  padding-right: 2px;
}

.filter-label {
  font-weight: 500;
  font-size: 14px;
}

.filter-btn {
  min-width: 80px;
  font-weight: 500;
}

:deep(.el-table) th {
  color: #666;
}

:deep(.el-table--default) .cell {
  padding-left: 2px;
  padding-right: 2px;
}

.tag-group {
  display: flex;
  justify-content: center;
}

/* 这些说不定以后还用得上 */
.tag-group > .dict-tag { margin-right: -1px; }
.tag-group > .dict-tag:not(:first-child):not(:last-child) :deep(.el-tag) { border-radius: 0; }
.tag-group > .dict-tag:first-child:last-child:last-child :deep(.el-tag) { border-radius: 4px; }

.tag-group > .dict-tag:first-child :deep(.el-tag) {
  border-top-right-radius: 0;
  border-bottom-right-radius: 0;
}

.tag-group > .dict-tag:last-child :deep(.el-tag) {
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
}

.count-info {
  flex: 1;
  display: flex;
  flex-wrap: wrap;
  line-height: 1.25;
  margin-left: 8px;
}

.count-info .value {
  color: red;
  cursor: pointer;
  text-decoration: underline;
}

:deep([class="caret-wrapper"]) {
  display: none;
}
</style>
